package com.joven.shelltest.utils.testfactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author wzj
 * @Date 2023-09-18 09:08
 **/
public class GatewayHandlerEnumFactory {

    private static final Map<Integer, GatewayEntity> GATEWAY_ENTITY_MAP = new HashMap<>();

    static {
        GatewayEnum[] values = GatewayEnum.values();
        for (GatewayEnum value : values) {
            GatewayEntity gatewayEntity = value.getGatewayEntity();
            GATEWAY_ENTITY_MAP.put(gatewayEntity.getHandlerId(), gatewayEntity);
        }
    }

    private static GatewayEntity getFirstGatewayEntity() {
        for (Map.Entry<Integer, GatewayEntity> entry : GATEWAY_ENTITY_MAP.entrySet()) {
            GatewayEntity value = entry.getValue();
            //  没有上一个handler的就是第一个
            if (Objects.isNull(value.getPreHandlerId())) {
                return value;
            }
        }
        return null;
    }

    public static GatewayHandler getFirstGatewayHandler() {
        GatewayEntity firstGatewayEntity = getFirstGatewayEntity();
        GatewayHandler firstGatewayHandler = newGatewayHandler(firstGatewayEntity);
        if (firstGatewayEntity == null || firstGatewayHandler == null) {
            return null;
        }
        GatewayEntity tempGatewayEntity = firstGatewayEntity;
        Integer nextHandlerId = null;
        GatewayHandler tempGatewayHandler = firstGatewayHandler;
        // 迭代遍历所有handler，以及将它们链接起来
        while ((nextHandlerId = tempGatewayEntity.getNextHandlerId()) != null) {
            GatewayEntity gatewayEntity = GATEWAY_ENTITY_MAP.get(nextHandlerId);
            GatewayHandler gatewayHandler = newGatewayHandler(gatewayEntity);
            if (Objects.isNull(gatewayHandler)) {
                break;
            }
            tempGatewayHandler.setNext(gatewayHandler);
            tempGatewayHandler = gatewayHandler;
            tempGatewayEntity = gatewayEntity;
        }
        // 返回第一个handler
        return firstGatewayHandler;

    }


    private static GatewayHandler newGatewayHandler(GatewayEntity firstGatewayEntity) {
        if (Objects.isNull(firstGatewayEntity)) {
            return null;
        }
        // 获取全限定类名
        String className = firstGatewayEntity.getConference();
        try {
            // 根据全限定类名，加载并初始化该类，即会初始化该类的静态段
            Class<?> clazz = Class.forName(className);
            return (GatewayHandler) clazz.newInstance();
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }
}
